import Footer from "@/components/Footer";
import { doFetch, postFetch } from "@/utils/doFetch";
import { LockOutlined, UserOutlined, RedoOutlined } from "@ant-design/icons";
import {
  LoginForm,
  ProFormCheckbox,
  ProFormText,
} from "@ant-design/pro-components";
import { history, useModel,useOutletContext } from "umi";
import { Card, Dropdown, message, Tabs, QRCode } from "antd";
import { useState } from "react";

const Login = () => {
  const {
    initialState: { currentUser, fetchUserInfo },
    setInitialState,
  } = useModel("@@initialState");
  const { mode } = useOutletContext();

  const handleSubmit = async (values) => {
    if (loginType === "account") {
      // 登录
      const msg = await doFetch({
        url: "/webtool/login",
        params: {
          user_name: values?.username,
          password: values?.password,
        },
      });
      if (msg.code === 0) {
        localStorage.setItem("TOKENSTRING", msg?.data);
        const currentUser = await fetchUserInfo();
        localStorage.setItem("ID", currentUser?.id);
        await setInitialState((s) => {
          return {
            ...s,
            fetchUserInfo,
            currentUser,
          };
        });
        history.push("/");
      }
    } else {
      // 登录
      const msg = await postFetch({
        url: "/webtool/v1/user",
        params: {
          user_name: values?.username,
          password: values?.password,
        },
      });
      if (msg.code === 0) {
        setLoginType("account");
      }
    }
  };

  const [loginType, setLoginType] = useState("account");

  return (
    <div
      className="noline"
      style={{
        display: "flex",
        flexDirection: "column",
        height: "100vh",
        overflow: "auto",
        backgroundImage:
          "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
        backgroundSize: "100% 100%",
      }}
    >
      <div
        style={{
          flex: "1",
          padding: "32px 0",
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: "75vw",
          }}
          logo={
            <img alt="logo" src="./logo.png" style={{ borderRadius: "50%" }} />
          }
          subTitle={"———ApanCRUD平台"}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values);
          }}
          submitter={{
            searchConfig: {
              submitText: loginType === 'account' ? '登录' : '注册',
            },
          }}
        >
          <Tabs
            activeKey={loginType}
            onChange={(activeKey) => setLoginType(activeKey)}
            items={[
              { label: "登录", key: "account" },
              { label: "注册", key: "phone" },
            ]}
          ></Tabs>
          {loginType === "account" && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: "large",
                  prefix: <UserOutlined />,
                }}
                placeholder={"用户名"}
                rules={[
                  {
                    required: true,
                    message: "请输入用户名!",
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: "large",
                  prefix: <LockOutlined />,
                }}
                placeholder={"密码"}
                rules={[
                  {
                    required: true,
                    message: "请输入密码！",
                  },
                ]}
              />
              <div
                style={{
                  marginBottom: 24,
                }}
              >
                <ProFormCheckbox noStyle name="autoLogin">
                  自动登录
                </ProFormCheckbox>
                <Dropdown
                  trigger={"click"}
                  placement="right"
                  dropdownRender={() => (
                    <div className="diycard" style={{ marginTop: -128 }}>
                      <img
                        src="./WechatIMG.jpeg"
                        alt=""
                        style={{ width: 240, margin: "2px 0 -2px 0" }}
                      />
                    </div>
                  )}
                >
                  <a
                    style={{
                      float: "right",
                    }}
                  >
                    忘记密码
                  </a>
                </Dropdown>
              </div>
            </>
          )}
          {loginType === 'phone' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'用户名'}
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <ProFormText.Password
                name="confirm"
                dependencies={['password']}
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'确认密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次密码不一致!'));
                    },
                  }),
                ]}
              />
            </>
          )}
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
